package com.lcz.authority.common.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcz.authority.common.domain.entity.DataInitializerEntity;
import com.lcz.authority.common.exception.ServiceException;
import com.lcz.authority.common.exception.constants.ErrorCodeConstants;
import com.lcz.authority.common.mapper.DataInitializerMapper;
import com.lcz.authority.common.service.impl.SysConfigServiceImpl;
import com.lcz.authority.common.utils.StringUtils;
import com.zhou.starter.jpacomment.service.AlterCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author lcz
 * @desc 数据初始化器
 * @mail lcz_0130@163.com
 * @date 2024/05/11
 */

@Component("DataInitializerConfig")
@Slf4j
public class DataInitializerConfig {

    @Value("${init.file}")
    String initFile;
    @Value("${spring.application.name}")
    String serviceName;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ResourceLoader resourceLoader;
    @Resource
    private DataInitializerMapper dataInitializerMapper;
    @Resource
    private AlterCommentService alterCommentService;
    @Resource
    private SysConfigServiceImpl sysConfigServiceimpl;

    @PostConstruct
    public void initData() {
        //判断是否执行初始化sql文件
        List<DataInitializerEntity> dataInitializers = dataInitializerMapper.selectList(new QueryWrapper<DataInitializerEntity>().eq("service_name", serviceName));
        if (!dataInitializers.isEmpty()) {
            log.info("数据库已经初始化完成");
            return;
        }
        try {
            // 读取原始文件
            BufferedReader reader = new BufferedReader(new InputStreamReader(resourceLoader.getResource(initFile).getInputStream(), StandardCharsets.UTF_8));
            String line;
            String schema = alterCommentService.getSchema();
            if (StringUtils.isNotBlank(schema)) {
                schema += ".";
            }
            while ((line = reader.readLine()) != null) {
                // 替换字符串
                String newLine = line.replace("#{schema}", schema);
                //如果newLine以/*开头就是注释文件不执行
                if (newLine.startsWith("/*") || StringUtils.isEmpty(newLine)) {
                    continue;
                }
                //判断这一行是否是；结尾，不是就拼接
                if (!newLine.endsWith(";")) {
                    newLine += " ";
                    String temp;
                    while ((temp = reader.readLine()) != null) {
                        newLine += temp;
                        if (temp.endsWith(";")) {
                            break;
                        }
                    }
                }
                // 注意：每行都是一个完整的SQL语句
                jdbcTemplate.execute(newLine);
            }
            log.info("数据库数据初始化成功...");
            // 关闭流
            reader.close();
        } catch (IOException e) {
            throw new ServiceException(ErrorCodeConstants.SQL_INIT_ERROR);
        }
        //设置系统初始化完成
        DataInitializerEntity dataInitializer = new DataInitializerEntity();
        dataInitializer.setServiceName(serviceName);
        dataInitializerMapper.insert(dataInitializer);
        log.info("{}数据库初始化信息完成", serviceName);

        sysConfigServiceimpl.loadingConfigCache();
    }
}

